package com.wh.service.storehousemanage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.api.Api;
import com.wh.mapper.initial.LocationMapper;
import com.wh.mapper.initial.ProductMapper;
import com.wh.mapper.instorehouse.PurchaseMapper;
import com.wh.mapper.instorehouse.ReceivingMapper;
import com.wh.mapper.stock.StockMapper;
import com.wh.mapper.instorehouse.PutInMapper;
import com.wh.mapper.storehousemanage.ShelvesMapper;
import com.wh.pojo.*;
import com.wh.vo.PageResult;
import com.wh.vo.QueryInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class ShelvesServiceImpl implements ShelvesService{
    @Autowired
    private ShelvesMapper shelvesMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private LocationMapper locationMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private PutInMapper putInMapper;

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private ReceivingMapper receivingMapper;


    @Override
    public Map<String, Object> getQuery(QueryInfo queryInfo) {

        QueryWrapper<Stock> stockQueryWrapper = new QueryWrapper<>();
        stockQueryWrapper.eq(StringUtils.hasLength(queryInfo.getBarCode()),"bar_code",queryInfo.getBarCode())
                .eq(StringUtils.hasLength(queryInfo.getFromLocationId()),"Location_id",queryInfo.getFromLocationId())
                .eq("status","待上架")
                .select("bar_code","location_id","available_quantity");
        List<Stock> stockList = stockMapper.selectList(stockQueryWrapper);

        QueryWrapper<Location> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.eq("status","空闲").ne("type","入库区").or().eq("status",queryInfo.getBarCode());

        List<Location> locationList = locationMapper.selectList(locationQueryWrapper);

        Map<String,Object> map = new HashMap<>();
        Set<String> barCodeSet = new HashSet<>();
        Set<String> locationIdSet = new HashSet<>();
        Set<String> fromLocationIdSet = new HashSet<>();
        for (Stock stock : stockList){
            barCodeSet.add(stock.getBarCode());
            fromLocationIdSet.add(stock.getLocationId());
        }

        for (Location location : locationList){
            locationIdSet.add(location.getLocationId());
        }

        locationIdSet.remove(queryInfo.getFromLocationId());
        fromLocationIdSet.remove(queryInfo.getLocationId());

        map.put("barCode",barCodeSet);
        map.put("locationId",locationIdSet);
        map.put("fromLocationId",fromLocationIdSet);
        map.put("availableQuantity",0);



        if (stockList.size()==1 && queryInfo.getCount()!=null && queryInfo.getCount()>stockList.get(0).getAvailableQuantity()){
            return new HashMap<>();
        }if (stockList.size()==1){
            map.replace("availableQuantity",stockList.get(0).getAvailableQuantity());
            return map;
        }else{
            return map;
        }
    }

    @Override
    public void addShelves(OnShelves onShelves) {
        QueryWrapper<Location> locationQueryWrapper = new QueryWrapper<>();
        String locationName = locationMapper.selectById(onShelves.getLocationId()).getName();
        String fromLocationName = locationMapper.selectById(onShelves.getFromLocationId()).getName();
        String productName = productMapper.selectById(onShelves.getBarCode()).getName();
        String createTime = new Api().getTime();

        onShelves.setFromLocationName(fromLocationName)
                .setLocationName(locationName)
                .setProductName(productName)
                .setCreateTime(createTime)
                .setStatus("待审核")
                .setCreateTime(new Api().getTime());

        shelvesMapper.insert(onShelves);

        Stock stock = stockMapper.selectById(onShelves.getFromLocationId());
        QueryWrapper<InStorehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("location_id",onShelves.getFromLocationId());
        InStorehouse inStorehouse = putInMapper.selectOne(queryWrapper);
        inStorehouse.setStatus("进行中");
        putInMapper.updateById(inStorehouse);

        stock.setAvailableQuantity(
                stock.getAvailableQuantity()-onShelves.getCount()
        ).setLockedQuantity(
                stock.getLockedQuantity()+onShelves.getCount()
        );

        stockMapper.updateById(stock);

        Location location = locationMapper.selectById(onShelves.getLocationId());
        location.setStatus(onShelves.getBarCode());
        locationMapper.updateById(location);


    }

    @Override
    public PageResult getShelves(PageResult pageResult) {
        Page<OnShelves> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<OnShelves> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(flag,"shelves_id",pageResult.getQuery());

        page = shelvesMapper.selectPage(page,queryWrapper);

        pageResult.setTotal((long) page.getRecords().size()).setRows(page.getRecords());
        return pageResult;
    }

    @Override
    public void deleteShelves(String id) {
        OnShelves onShelves = shelvesMapper.selectById(id);

        //判断库位是否空闲,修改状态
        QueryWrapper<OnShelves> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("location_id",onShelves.getLocationId());
        List<OnShelves> list = shelvesMapper.selectList(queryWrapper);
        if (list.size() == 1){
            Location location = locationMapper.selectById(onShelves.getLocationId());
            location.setStatus("空闲");
            locationMapper.updateById(location);
        }

        //更新源货位数据
        Stock stock = stockMapper.selectById(onShelves.getFromLocationId());
        stock.setAvailableQuantity(stock.getAvailableQuantity() + onShelves.getCount())
                .setLockedQuantity(stock.getLockedQuantity() - onShelves.getCount());
        stockMapper.updateById(stock);

        shelvesMapper.deleteById(id);
    }

    @Override
    public void updataShelves(OnShelves onShelves) throws Exception {


        if (onShelves.getStatus().equals("已审核")){
            check(onShelves);
            onShelves.setCheckTime(new Api().getTime());
        }else if (onShelves.getStatus().equals("待审核")){
            cancelCheck(onShelves);
            onShelves.setCheckTime("").setCheckPerson("");
        }
        shelvesMapper.updateById(onShelves);

        Stock stock = stockMapper.selectById(onShelves.getFromLocationId());
        if (stock == null) return;
        QueryWrapper<OnShelves> onShelvesQueryWrapper = new QueryWrapper<>();
        onShelvesQueryWrapper.eq("from_location_id",onShelves.getFromLocationId()).eq("status","已审核");
        List<OnShelves> onShelvesList = shelvesMapper.selectList(onShelvesQueryWrapper);
        Integer lockedQuantity = 0;
        for (OnShelves onShelves1 : onShelvesList){
            lockedQuantity += onShelves1.getCount();
        }

        if (stock.getAvailableQuantity()==0 && stock.getLockedQuantity() == lockedQuantity){
            deleteStock(onShelves.getFromLocationId());
        }
    }

    public void deleteStock(String locationId){
        Stock stock = stockMapper.selectById(locationId);
        QueryWrapper<InStorehouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("location_id",locationId);
        InStorehouse inStorehouse = putInMapper.selectOne(queryWrapper);
        if (stock.getLockedQuantity() == 0){
            inStorehouse.setStatus("已审核");
        }
        stockMapper.deleteById(locationId);

        Location location = locationMapper.selectById(locationId);
        location.setStatus("空闲");
        locationMapper.updateById(location);

    }

    public void check(OnShelves onShelves){
        Stock stock = stockMapper.selectById(onShelves.getFromLocationId());


        QueryWrapper<Stock> stockQueryWrapper = new QueryWrapper<>();
        stockQueryWrapper.eq("location_id",onShelves.getLocationId());
        Integer num = stockMapper.selectCount(stockQueryWrapper);
        System.out.println(num);
        Stock newStock;
        if (num == 0) {
            newStock = new Stock();
            newStock.setAvailableQuantity(onShelves.getCount())
                    .setTotalQuantity(onShelves.getCount())
                    .setBarCode(onShelves.getBarCode())
                    .setLockedQuantity(0)
                    .setInStorehouseId(stock.getInStorehouseId())
                    .setLocationId(onShelves.getLocationId())
                    .setLocationName(onShelves.getLocationName())
                    .setProductName(onShelves.getProductName())
                    .setStatus("已上架");
            stockMapper.insert(newStock);


            Location location = locationMapper.selectById(onShelves.getLocationId());
            location.setStatus(onShelves.getBarCode());
            locationMapper.updateById(location);

        }else {
            newStock = stockMapper.selectById(onShelves.getLocationId());
            newStock.setTotalQuantity(onShelves.getCount()+newStock.getAvailableQuantity())
                    .setAvailableQuantity(onShelves.getCount()+newStock.getAvailableQuantity());
            stockMapper.updateById(newStock);
        }



    }

    public void cancelCheck(OnShelves onShelves) throws Exception {
        //获取商品库存
        Stock stock2 = stockMapper.selectById(onShelves.getLocationId());
        //可用数量
        Integer availableQuantity = stock2.getAvailableQuantity()-onShelves.getCount();

        if (stock2.getAvailableQuantity()<onShelves.getCount()) throw new Exception("数量不足") ;


        QueryWrapper<Stock> stockQueryWrapper = new QueryWrapper<>();
        stockQueryWrapper.eq("location_id",onShelves.getFromLocationId());
        Stock stock = new Stock();
        Integer c = stockMapper.selectCount(stockQueryWrapper);
        if (stockMapper.selectCount(stockQueryWrapper) == 0) {
            InStorehouse inStorehouse = putInMapper.selectById(stock2.getInStorehouseId());
            Receiving receiving = receivingMapper.selectById(inStorehouse.getReceivingId());
            Purchase purchase = purchaseMapper.selectById(receiving.getPurchaseId());

            stock.setInStorehouseId(stock2.getInStorehouseId())
                    .setLocationId(onShelves.getFromLocationId())
                    .setLocationName(onShelves.getFromLocationName())
                    .setBarCode(stock2.getBarCode())
                    .setProductName(stock2.getProductName())
                    .setTotalQuantity(purchase.getCount())
                    .setAvailableQuantity(0)
                    .setLockedQuantity(purchase.getCount())
                    .setStatus("待上架");
            stockMapper.insert(stock);
        }

        if ( availableQuantity == 0){
            stockMapper.deleteById(onShelves.getLocationId());
            Location location = locationMapper.selectById(onShelves.getLocationId());
            location.setStatus("空闲");
            locationMapper.updateById(location);
        }else {
            stock2.setTotalQuantity(stock2.getTotalQuantity()-stock2.getAvailableQuantity()+availableQuantity)
                    .setAvailableQuantity(availableQuantity);
            stockMapper.updateById(stock2);
        }

    }


}
